package com.flnet.spsys.service.impl;

import com.aliyun.oss.OSSClient;
import com.flnet.spsys.config.ConstantPropertiesUtils;
import com.flnet.spsys.service.OssService;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String upload(MultipartFile file) {
        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        try{
            //创建oss实例
            OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
            //获取上传文件流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName=file.getOriginalFilename();
            //随机值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            //文件名称添加随机值,防止重名
            fileName=uuid+fileName;
            //把文件按照日期分类
            String filePath = new DateTime().toString("yyyy/MM/dd");
            //拼接
            fileName=filePath+"/"+fileName;
            //文件上传至阿里云
            //调用oos方法实现上传
            //第一个参数Bucket名称
            //第二个参数 上传到oss文件路径和文件名称 aa/bb/cc.jpg
            //第三个参数 上传文件输入流
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //把上传之后的文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            String url = "https://"+bucketName+"."+endPoint+"/"+fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }
}
